import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/XDialogs/dialog_utils.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/components/XStatefulWidget/XStatefulWidget.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/EntityWidget/common_fun.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/target/base/team.dart';
import 'package:orginone/dart/core/target/innerTeam/department.dart';
import 'package:orginone/dart/core/target/outTeam/cohort.dart';
import 'package:orginone/dart/core/target/outTeam/group.dart';
import 'package:orginone/dart/core/target/person.dart';
import 'package:orginone/dart/core/target/team/company.dart';
import 'package:orginone/main.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/log/log_util.dart';
import '../ListSearchWidget/ListSearchWidget.dart';
import '../XButtonBar/XButtonBar.dart';

/// 好友/成员列表页面
class MemberListWidget extends XStatefulWidget {
  MemberListWidget({super.key, super.data});

  @override
  State<StatefulWidget> createState() => _MemberListState();
}

class _MemberListState extends XStatefulState<MemberListWidget, dynamic> {
  late final String _emitterKey;
  ScrollController _scrollController = ScrollController();
  List<XTarget> members = [];

  @override
  initState() {
    super.initState();
    if (widget.data is ITeam) {
      ITeam team = widget.data;
      _emitterKey = team.subscribe((key, args) {
        if (mounted) {
          setState(() {
            //刷新页面
          });
        }
      }, false);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (widget.data is ITeam) {
      ITeam team = widget.data as ITeam;
      team.unsubscribe(_emitterKey);
    }
  }

  @override
  Widget buildWidget(BuildContext context, dynamic data) {
    if (data is IPerson) {
      members = loadMembers(data).toSet().toList();
    } else if (data is ICompany) {
      members = loadMembers(data).toSet().toList();
    } else if (data is IDepartment) {
      members = loadMembers(data).toSet().toList();
    } else if (data is ICohort) {
      members = loadMembers(data).toSet().toList();
    } else if (data is IGroup) {
      members = loadMembers(data).toSet().toList();
    } else if (data is ISession) {
      members = loadMembers(data).toSet().toList();
    }
    Widget content = Container(
        margin: EdgeInsets.symmetric(vertical: 1.h),
        decoration: const BoxDecoration(color: Colors.white),
        child: Stack(
          children: [
            _buildList(context),
            (hasAuth(data))
                ? XButtonBar(
                    listAction: [
                      ActionModel(
                          title: isSelf ? "添加好友" : "邀请成员",
                          onTap: () {
                            if (isSelf) {
                              showSearchBottomSheet(
                                  navigatorKey.currentState!.context,
                                  TargetType.person,
                                  title: "添加好友",
                                  hint: "请输入用户的账号",
                                  onSelected: (targets) async {
                                bool success = false;
                                if (targets.isNotEmpty) {
                                  success = await relationCtrl.user!
                                      .applyJoin(targets);
                                  if (success) {
                                    ToastUtils.showMsg(msg: "发送申请成功");
                                  }
                                }
                              });
                            } else {
                              showSearchBottomSheet(context, TargetType.person,
                                  title: "邀请成员", hint: "请输入用户的账号",
                                  onSelected: (targets) async {
                                bool success = false;
                                dynamic dataTargets = data.target;
                                if (targets.isNotEmpty) {
                                  success =
                                      await dataTargets.pullMembers(targets);
                                  if (success) {
                                    setState(() {});
                                  }
                                }
                              });
                            }
                          }),
                    ],
                  )
                : Container()
          ],
        ));
    return content;
  }

  bool hasAuth(dynamic data) {
    bool res = false;
    if (data is ISession) {
      data = data.target;
    }
    if (data is ITeam && data.hasRelationAuth() && data.id != data.userId) {
      res = true;
    }
    if (isSelf) {
      res = true;
    }

    return res;
  }

  bool get isSelf {
    return data.id == relationCtrl.user?.id;
  }

  // List<XTarget> loadFriends(IPerson user) {
  //   return user.members;
  // }

  List<XTarget> loadMembers(dynamic company) {
    return company.members;
  }

  Widget _buildConfirmDialog(BuildContext context, Function confirmFun,
      {String userName = "成员"}) {
    return CupertinoAlertDialog(
      title: Text("确认移除$userName？"),
      content: const Text(""),
      actions: <Widget>[
        CupertinoDialogAction(
          child: const Text('取消'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        CupertinoDialogAction(
          child: const Text('确认'),
          onPressed: () {
            confirmFun();
          },
        ),
      ],
    );
  }

  _removeFriend(dynamic dataitem) {
    return AlertDialogUtils.buildBottomModal(
        context,
        [
          ActionModel(
              title: "移除好友",
              onTap: () async {
                showDialog(
                    context: context,
                    builder: (BuildContext context) => Center(
                          child: Material(
                              color: Colors.transparent,
                              child: _buildConfirmDialog(context, () async {
                                if (dataitem is XTarget) {
                                  bool success = await relationCtrl.user!
                                      .removeMembers([dataitem]);
                                  if (success) {
                                    ToastUtils.showMsg(msg: "移除好友成功");
                                    setState(() {});
                                  } else {
                                    ToastUtils.showMsg(msg: "移除失败，请稍后重试");
                                  }
                                  RoutePages.back(context);
                                }
                              }, userName: dataitem.name ?? "成员")),
                        ),
                    barrierColor: Colors.black.withOpacity(0.6));
              })
        ],
        isNeedPop: false);
  }

  _removeMember(dynamic dataitem) {
    return AlertDialogUtils.buildBottomModal(
        context,
        [
          ActionModel(
              title: "移除成员",
              onTap: () async {
                showDialog(
                    context: context,
                    builder: (context) => Center(
                          child: Material(
                              color: Colors.transparent,
                              child: _buildConfirmDialog(context, () async {
                                dynamic dataTargets = data.target;
                                if (dataitem is XTarget) {
                                  bool success = await dataTargets
                                      .removeMembers([dataitem]);
                                  if (success) {
                                    ToastUtils.showMsg(msg: "移除成员成功");
                                    setState(() {});
                                  } else {
                                    ToastUtils.showMsg(msg: "移除失败，请稍后重试");
                                  }
                                  RoutePages.back(context);
                                }
                              }, userName: dataitem.name ?? "成员")),
                        ),
                    barrierColor: Colors.black.withOpacity(0.6));
              })
        ],
        isNeedPop: false);
  }

  loadDataMore(String searchText) async {
    // ITeam team = widget.data as ITeam;
    // team.loadMembers();
    // members.addAll((await relationCtrl.user?.loadMembers()) as Iterable<XTarget>);
    await relationCtrl.user?.loadMembers();
    setState(() {});
  }

  _buildList(BuildContext context) {
    return Container(
      color: XColors.white,
      child: ListSearchWidget(
        initDatas: members,
        onInitLoad:  ([String? searchText]) {
          return members;
        },
        onLoad: ([String? searchText]) {
          loadDataMore(searchText??"");
          return members;
        },
        scrollController: _scrollController,
        getAction: (dynamic dataitem) {
          return Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                if (dataitem.typeName == TargetType.person.label)
                  GestureDetector(
                      onTap: () async {
                        //打电话
                        String phone = dataitem.code;
                        RegExp regex = RegExp(Constants.accountRegex);

                        if (!regex.hasMatch(phone)) {
                          ToastUtils.showMsg(msg: "获取用户手机号失败！");
                          return;
                        }
                        launchPhone(phone);
                      },
                      child: Container(
                          padding: const EdgeInsets.only(left: 8, right: 8),
                          child: XImage.localImage(XImage.call))),
                if (hasAuth(data))
                  GestureDetector(
                      onTap: () {
                        XLogUtil.d('>>>>>>======移除成员');
                        if (hasAuth(data)) {
                          if (isSelf) {
                            _removeFriend(dataitem);
                          } else {
                            _removeMember(dataitem);
                          }
                        } else {
                          ToastUtils.showMsg(msg: "敬请期待！！！");
                        }
                      },
                      child: XImage.localImage(XImage.moreAction))
              ]);
        },
        onTap: (dynamic data, List children) {
          XLogUtil.d('>>>>>>======点击了列表项 ${data.name}');
          /*if (children.isNotEmpty) {
            RoutePages.jumpRelation(parentData: data, listDatas: children);
          } else */if (data is XTarget) {
            ISession? session = relationCtrl.user?.findMemberChat(data.id);
            if (null != session) {
              RoutePages.jumpRelationInfo(context: context, data: session);
            } else {
              // 待完善新建的会话
              RoutePages.jumpRelationInfo(context: context, data: data);
            }
          } else if (data is Map && data.containsKey('id')) {
            RoutePages.jumpRelationInfo(context: context, data: data);
          }
        },
      ),
    );
    // return ListWidget(
    //   initDatas: datas,
    //   getDatas: ([dynamic parentData]) {
    //     if (null == parentData) {
    //       return datas;
    //     }
    //     return [];
    //   },
    //   getAction: (dynamic dataitem) {
    //     return Row(
    //         mainAxisSize: MainAxisSize.min,
    //         mainAxisAlignment: MainAxisAlignment.end,
    //         crossAxisAlignment: CrossAxisAlignment.center,
    //         children: [
    //           // GestureDetector(
    //           //     onTap: () async {
    //           //       ISession? session = relationCtrl.user!.chats
    //           //           .firstWhereOrNull(
    //           //               (element) => element.id == dataitem.id);
    //           //       if (session != null) {
    //           //         RoutePages.jumpChatSession(data: session);
    //           //       }
    //           //     },
    //           //     child: Container(
    //           //         padding: const EdgeInsets.only(left: 8, right: 8),
    //           //         child: XImage.localImage(XImage.sendMsg))),
    //           if (dataitem.typeName == TargetType.person.label)
    //             GestureDetector(
    //                 onTap: () async {
    //                   //打电话
    //                   String phone = dataitem.code;
    //                   RegExp regex = RegExp(Constants.accountRegex);
    //
    //                   if (!regex.hasMatch(phone)) {
    //                     ToastUtils.showMsg(msg: "获取用户手机号失败！");
    //                     return;
    //                   }
    //                   launchPhone(phone);
    //                 },
    //                 child: Container(
    //                     padding: const EdgeInsets.only(left: 8, right: 8),
    //                     child: XImage.localImage(XImage.call))),
    //           if (hasAuth(data))
    //             GestureDetector(
    //                 onTap: () {
    //                   LogUtil.d('>>>>>>======移除成员');
    //                   if (hasAuth(data)) {
    //                     if (isSelf) {
    //                       _removeFriend(dataitem);
    //                     } else {
    //                       _removeMember(dataitem);
    //                     }
    //                   } else {
    //                     ToastUtils.showMsg(msg: "敬请期待！！！");
    //                   }
    //                 },
    //                 child: XImage.localImage(XImage.moreAction))
    //         ]);
    //   },
    //   onTap: (dynamic data, List children) {
    //     LogUtil.d('>>>>>>======点击了列表项 ${data.name}');
    //     if (children.isNotEmpty) {
    //       RoutePages.jumpRelation(parentData: data, listDatas: children);
    //     } else if (data is XTarget) {
    //       ISession? session = relationCtrl.user?.findMemberChat(data.id);
    //       if (null != session) {
    //         RoutePages.jumpRelationInfo(context: context, data: session);
    //       } else {
    //         // 待完善新建的会话
    //         RoutePages.jumpRelationInfo(context: context, data: data);
    //       }
    //     } else if (data is Map && data.containsKey('id')) {
    //       RoutePages.jumpRelationInfo(context: context, data: data);
    //     }
    //   },
    // );
  }

  Future<List<XTarget>?> search(String code) async {
    List<XTarget>? resultList;
    if (code.isEmpty) {
      resultList = relationCtrl.user!.members;
    } else {
      resultList = members.where((item) => (item.name.contains(code))).toList();
    }
    return resultList;
  }
}
